package com.geeklei.media.ui;

import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.geeklei.media.ui.common.AnimatorFactory;
import com.geeklei.media.ui.common.ErrorEvent;
import com.geeklei.media.ui.controller.MediaController;
import com.geeklei.media.ui.controller.OrientationUpdater;
import com.geeklei.media.ui.menu.Menu;
import com.geeklei.media.ui.menu.MenuActionListener;
import com.geeklei.media.ui.menu.MenuFactory;
import com.geeklei.media.ui.menu.MenuIds;
import com.geeklei.media.ui.menu.MenuItem;
import com.geeklei.media.ui.menu.popup.BaseMenuPopup;
import com.geeklei.media.ui.menu.popup.ItemWraper;
import com.geeklei.media.ui.menu.popup.ListPopupWindow;
import com.geeklei.media.ui.menu.popup.OnShowHideListener;
import com.geeklei.media.ui.menu.popup.PopListAdapter;
import com.geeklei.media.ui.menu.popup.SettingsPopup;
import com.geeklei.media.ui.widget.GestureBrightness;
import com.geeklei.media.ui.widget.GestureSeek;
import com.geeklei.media.ui.widget.GestureVolumn;
import com.geeklei.media.ui.widget.StatusBar;
import com.geeklei.videoplayer.GeekleiVideoView;

import java.util.ArrayList;
import java.util.List;

import tv.danmaku.ijk.media.player.AbstractMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by leixun on 16/5/31.
 */
public class FullScreenVideoController extends RelativeLayout implements IVideoLifeCycle, ControllerView.OnControlEventListener {

    boolean hideFlag = false;
    public static final int STATE_FULL = 4;
    public static final int STATE_IDLE = 0;
    public static final int STATE_LOADING = 2;
    public static final int STATE_LOCK_SCREEN = 1;
    public static final int STATE_MILINK = 3;
    public static final String TAG = "FullScreenVideoController";
    private Activity mActivity;
    private RelativeLayout mAnchor;
    private List<Animator> mAnimators = new ArrayList();
    private Runnable mAutoDismiss = new Runnable() {
        public void run() {
            com.geeklei.media.ui.FullScreenVideoController.this.hideController();
        }
    };
    private GestureBrightness mBrightness;
    //    private CoreFragment mCoreFragment;
    private Runnable mGoneRunner = new Runnable() {
        public void run() {
            com.geeklei.media.ui.FullScreenVideoController.this.setVisibility(View.GONE);
        }
    };

    private boolean mIsScreenLocked = false;
    private boolean mIsShowing = false;
    private boolean mIsVideoLoading = false;
    private View mLeftLayout;
    private ImageView mLeftMask;
    private MediaController mMediaController;
    private Menu mMenu;
    private StatusBar mStatusBar;
    private SettingsPopup mSettingsPopup;
    private ListPopupWindow mPlayListPopup;
    private PopListAdapter mPlayListPopupAdapter;
    private OnClickListener mOnClickListener = new OnClickListener() {
        public void onClick(View view) {
            if (view == com.geeklei.media.ui.FullScreenVideoController.this.mScreenLocker) {
                if (com.geeklei.media.ui.FullScreenVideoController.this.mIsScreenLocked) {
                    com.geeklei.media.ui.FullScreenVideoController.this.enterUnlockScreen();
                } else {
                    com.geeklei.media.ui.FullScreenVideoController.this.enterLockScreen();
                }
                com.geeklei.media.ui.FullScreenVideoController.this.mIsScreenLocked = !com.geeklei.media.ui.FullScreenVideoController.this.mIsScreenLocked;
            }
        }
    };
    protected OnShowHideListener<BaseMenuPopup> mMenuShowHideListener = new OnShowHideListener<BaseMenuPopup>() {
        public void onShow(BaseMenuPopup baseMenuPopup) {
            hideController();
        }

        public void onHide(BaseMenuPopup baseMenuPopup) {
        }
    };
    private OrientationUpdater mOrientationUpdater;
    private AbstractMediaPlayer mPlayer;
    private ImageView mScreenLocker;
    private GestureSeek mSeek;
    private Handler mUiHandler = new Handler(Looper.getMainLooper());
    private GestureVolumn mVolumn;
    private IUserEventListener mUserEventListener;

    public FullScreenVideoController(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
    }

    public FullScreenVideoController(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
    }

    public FullScreenVideoController(Context context) {
        super(context);
    }

    public void attachActivity(Activity activity, RelativeLayout relativeLayout, OrientationUpdater orientationUpdater) {
        this.mActivity = activity;
        this.mAnchor = relativeLayout;
        this.mStatusBar.attachActivity(activity);
        this.mOrientationUpdater = orientationUpdater;
    }

    public void attachMediaPlayer(AbstractMediaPlayer mPlayer, IUserEventListener userEventListener) {
        if (this.mPlayer == null) {
            this.mPlayer = mPlayer;
            this.mUserEventListener = userEventListener;
            mMediaController.attachPlayer(mPlayer, userEventListener);
        }
        this.mStatusBar.attachSpeed(userEventListener, mAnchor, mMenuShowHideListener);
    }

    public void updateStatus(String titleName, String subTitleName) {
        if (mStatusBar != null) {
            mStatusBar.updateStatus(titleName, subTitleName);
        }
    }

    public void updateSpeedStatus(float speed) {
        mMediaController.updateSppedStatus(speed);
        mStatusBar.updateSppedStatus(speed);
    }

    public void updatePlayingState() {
        if (mMediaController != null) {
            mMediaController.start();
        }
    }

    public boolean dispatchTouchEvent(MotionEvent motionEvent) {
        resetAutoDismiss();
        return super.dispatchTouchEvent(motionEvent);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void enterUnlockScreen() {
        this.mScreenLocker.setImageResource(R.drawable.vp_screen_locker_bg);
        this.mScreenLocker.setTranslationX((float) getResources().getDimensionPixelSize(R.dimen.vp_mc_screen_locker_margin_left));
        this.mLeftMask.setVisibility(VISIBLE);
        animateForLocker(false);
        if (this.mOrientationUpdater != null) {
            this.mOrientationUpdater.enableRotation();
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void enterLockScreen() {
        this.mScreenLocker.setTranslationX((float) getResources().getDimensionPixelSize(R.dimen.vp_mc_screen_locker_big_margin_left));
        this.mScreenLocker.setImageResource(R.drawable.screen_lock_icon_big);
        this.mLeftMask.setVisibility(GONE);
        animateForLocker(true);
        if (this.mOrientationUpdater != null) {
            this.mOrientationUpdater.disableRotation();
        }
    }

    public void showLockScreen() {
        moveToState(STATE_LOCK_SCREEN);
        //延迟消失
        mUiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mLeftLayout.getVisibility() == VISIBLE) {
                    mLeftLayout.setVisibility(View.GONE);
                }
            }
        }, 3000);
    }

    public void hideScreenLocker() {
        if (this.mScreenLocker != null) {
            this.mScreenLocker.setVisibility(GONE);
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void resetScreenLocker() {
        this.mScreenLocker.setVisibility(VISIBLE);
        this.mScreenLocker.setImageResource(R.drawable.vp_screen_locker_bg);
        this.mScreenLocker.setTranslationX((float) getResources().getDimensionPixelSize(R.dimen.vp_mc_screen_locker_margin_left));
        this.mLeftMask.setVisibility(VISIBLE);
    }

    protected void onFinishInflate() {
        super.onFinishInflate();
        this.mMediaController = (MediaController) findViewById(R.id.media_controller);
        this.mMediaController.setVisibility(View.GONE);
        this.mLeftLayout = findViewById(R.id.left_layout);
        this.mLeftMask = (ImageView) findViewById(R.id.left_mask);
        this.mScreenLocker = (ImageView) findViewById(R.id.vp_screen_locker);
        this.mScreenLocker.setOnClickListener(this.mOnClickListener);
        this.mStatusBar = (StatusBar) findViewById(R.id.status_bar);
        this.mMenu = (Menu) findViewById(R.id.vp_menu);
        setVisibility(View.GONE);
    }


    @Override
    public void onTap(int i) {
        if (i == ControllerView.OnControlEventListener.REGION_LEFT) {
            adjustBrightness(0.0f);
        } else if (i == ControllerView.OnControlEventListener.REGION_RIGHT) {
            adjustVolumn(0.0f);
        } else if (this.mPlayer != null) {
            toggleMe();
        }
    }

    @Override
    public void onTouchMove(int direction, float movedX, float movedY) {
        if (direction == ControllerView.OnControlEventListener.REGION_LEFT) {
            adjustBrightness(movedY);
        } else if (direction == ControllerView.OnControlEventListener.REGION_RIGHT) {
            adjustVolumn(movedY);
        } else if (direction == ControllerView.OnControlEventListener.REGION_CENTER && isSeekGestureEnable()) {
            adjustSeekStart(movedX);
        }
    }

    @Override
    public void onTouchUp(int i) {
        if (i == ControllerView.OnControlEventListener.REGION_CENTER && isSeekGestureEnable()) {
            adjustSeekEnd();
        }
    }

    private boolean isSeekGestureEnable() {
        if (this.mIsVideoLoading || this.mPlayer == null || mIsScreenLocked) {
            return false;
        }
        return true;
    }

    @Override
    public void onAdsPlayEnd(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onAdsPlayStart(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onBufferingEnd(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onBufferingPercent(GeekleiVideoView iVideoView, int i) {

    }

    @Override
    public void onBufferingStart(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onCompletion(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onEpLoadingStart() {

    }

    @Override
    public void onPrepared(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onVideoLoadingStart(GeekleiVideoView iVideoView) {

    }

    @Override
    public void onInfoListener(GeekleiVideoView iVideoView, int what, int extras) {

    }

    private void adjustBrightness(float f) {
        if (!this.mIsScreenLocked) {
            if (this.mVolumn != null) {
                this.mVolumn.hide();
            }
            if (this.mBrightness == null) {
                this.mBrightness = GestureBrightness.create(this.mAnchor);
            }
            this.mBrightness.adjustBrightness(this.mActivity, f);
        }
    }

    private void adjustVolumn(float f) {
        if (!this.mIsScreenLocked) {
            if (this.mBrightness != null) {
                this.mBrightness.hide();
            }
            if (this.mVolumn == null) {
                this.mVolumn = GestureVolumn.create(this.mAnchor);
            }
            this.mVolumn.adjustVolume(this.mActivity, f);
        }
    }

    private void adjustSeekStart(float movedX) {
        cancelProgressTimer();
        if (!this.mIsScreenLocked) {
            if (this.mBrightness != null) {
                this.mBrightness.hide();
            }
            if (this.mVolumn != null) {
                this.mVolumn.hide();
            }
            if (this.mSeek == null) {
                this.mSeek = GestureSeek.create(this.mAnchor, this.mMediaController);
            }
            this.mSeek.adjustSeekStart(movedX);
        }
    }

    private void adjustSeekEnd() {
        startProgressTimer();
        if (this.mSeek != null) {
            this.mSeek.adjustSeekEnd();
        }
    }

    public void cancelProgressTimer() {
        mMediaController.cancelProgressTimer();
    }

    private void startProgressTimer() {
        mMediaController.startProgressTimer();
    }

    public void toggleMe() {
        if (this.mIsShowing) {
            hideController();
        } else {
            showController(true);
        }
    }

    public void hideController() {
        if (this.mIsShowing) {
            this.mIsShowing = false;

            this.mUiHandler.removeCallbacks(this.mAutoDismiss);
            this.mUiHandler.removeCallbacks(this.mGoneRunner);
            this.mUiHandler.postDelayed(this.mGoneRunner, 450);
            animateOut();
        }
    }

    public void hidePhoneStatusBar() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar
        if (Build.VERSION.SDK_INT >= 19) {
            uiFlags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        if (Build.VERSION.SDK_INT >= 11) {
            mActivity.getWindow().getDecorView().setSystemUiVisibility(uiFlags);
        }
    }

    public void showController(boolean resetAutoDismiss) {
        hidePhoneStatusBar();
        if (!this.mIsShowing) {

            this.mIsShowing = true;
            setVisibility(VISIBLE);
            clearDismissRunner();
            refreshViews();
            if (this.mIsScreenLocked) {
                moveToState(STATE_LOCK_SCREEN);
                resetAutoDismiss();
            } else if (this.mIsVideoLoading) {
                moveToState(STATE_LOADING);
            } else {
                moveToState(STATE_FULL);
                if (resetAutoDismiss) {
                    resetAutoDismiss();
                }
            }
            invalidate();
            bringToFront();
            requestLayout();
            ItemWraper currentSpeed = mUserEventListener.getCurrentSpeed();
            if (currentSpeed != null) {
                CharSequence speedStr = currentSpeed.getSource().subSequence(0, currentSpeed.getSource().length() - 1);
                float spped = Float.valueOf((String) speedStr);
                updateSpeedStatus(spped);
            }
        }
    }

    private void refreshViews() {
        boolean mediaControllerFlag = false;
        this.mMenu.setMenuActionListener(new MenuActionListener() {
            @Override
            public void onMenuClick(MenuItem menuItem) {
                if (menuItem.getId() == 0) {
                    mSettingsPopup = new SettingsPopup(mActivity);
                    mSettingsPopup.setShowHideListener(mMenuShowHideListener);
                    mSettingsPopup.show(mAnchor);
                } else if (menuItem.getId() == MenuIds.MENU_ID_ONLINE_EP) {
                    if (mUserEventListener == null) {
                        return;
                    }
                    mPlayListPopupAdapter = new PopListAdapter(mActivity);
                    mPlayListPopup = new ListPopupWindow(mActivity, R.string.vp_select_ci, mPlayListPopupAdapter);
                    mPlayListPopup.setSources(mUserEventListener.getPlayList());
                    mPlayListPopup.setOnSourceSelectListener(mUserEventListener.getPlaySelectListener());
                    mPlayListPopup.setCurrentSource(mUserEventListener.getCurrentPlay());
                    mPlayListPopup.setShowHideListener(mMenuShowHideListener);
                    mPlayListPopup.show(mAnchor);
                } else if (menuItem.getId() == MenuIds.MENU_ID_SPEED_MENU) {

                }
            }
        });
        List<MenuItem> arrayList = new ArrayList();
        arrayList.add(MenuFactory.createSetting());
        arrayList.add(MenuFactory.createEp());
//        arrayList.add(MenuFactory.createSpeedMenu());
        this.mMenu.setItems(arrayList);
        this.mMediaController.setSeekBarEnable(true);
    }

    private void resetAutoDismiss() {
        this.mUiHandler.removeCallbacks(this.mAutoDismiss);
        this.mUiHandler.postDelayed(this.mAutoDismiss, 8000);
    }

    private void moveToState(int i) {
        clearAnimations();
        switch (i) {
            case STATE_IDLE:
                animateOut();
                return;
            case STATE_LOCK_SCREEN:
                this.mStatusBar.setVisibility(GONE);
                this.mMenu.setVisibility(GONE);
                this.mMediaController.setVisibility(GONE);
                this.mLeftLayout.setVisibility(VISIBLE);
                return;
            case STATE_LOADING:
                this.mLeftLayout.setVisibility(VISIBLE);
                this.mMenu.setVisibility(VISIBLE);
                this.mMediaController.setVisibility(VISIBLE);
                this.mAnimators.add(AnimatorFactory.animateInTopView(this.mStatusBar));
                return;
            case STATE_MILINK:
                this.mLeftLayout.setVisibility(GONE);
                this.mAnimators.add(AnimatorFactory.animateInTopView(this.mStatusBar));
                this.mAnimators.add(AnimatorFactory.animateInBottomView(this.mMediaController));
                this.mAnimators.add(AnimatorFactory.animateInRightView(this.mMenu));
                return;
            case STATE_FULL:
                this.mAnimators.add(AnimatorFactory.animateInTopView(this.mStatusBar));
                this.mAnimators.add(AnimatorFactory.animateInBottomView(this.mMediaController));
                this.mAnimators.add(AnimatorFactory.animateInLeftView(this.mLeftLayout));
                this.mAnimators.add(AnimatorFactory.animateInRightView(this.mMenu));
                return;
            default:
                return;
        }
    }

    private void clearDismissRunner() {
        this.mUiHandler.removeCallbacks(this.mGoneRunner);
        this.mUiHandler.removeCallbacks(this.mAutoDismiss);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void clearAnimations() {
        for (Animator end : this.mAnimators) {
            end.end();
        }
        this.mAnimators.clear();
    }

    private void animateOut() {
        clearAnimations();
        if (this.mIsScreenLocked) {
            this.mLeftLayout.setVisibility(GONE);
            this.mUiHandler.removeCallbacks(this.mGoneRunner);
            setVisibility(VISIBLE);
            return;
        }
        if (this.mStatusBar.getVisibility() == VISIBLE) {
            this.mAnimators.add(AnimatorFactory.animateOutTopView(this.mStatusBar));
        }
        if (this.mMediaController.getVisibility() == VISIBLE) {
            this.mAnimators.add(AnimatorFactory.animateOutBottomView(this.mMediaController));
        }
        if (this.mMenu.getVisibility() == VISIBLE) {
            this.mAnimators.add(AnimatorFactory.animateOutRightView(this.mMenu));
        }
        if (this.mLeftLayout.getVisibility() == VISIBLE) {
            this.mAnimators.add(AnimatorFactory.animateOutLeftView(this.mLeftLayout));
        }
    }

    private void animateForLocker(boolean z) {
        clearAnimations();
        if (z) {
            if (this.mStatusBar.getVisibility() == VISIBLE) {
                this.mAnimators.add(AnimatorFactory.animateOutTopView(this.mStatusBar));
            }
            if (this.mMediaController.getVisibility() == VISIBLE) {
                this.mAnimators.add(AnimatorFactory.animateOutBottomView(this.mMediaController));
            }
            if (this.mMenu.getVisibility() == VISIBLE) {
                this.mAnimators.add(AnimatorFactory.animateOutRightView(this.mMenu));
                return;
            }
            return;
        }
        this.mAnimators.add(AnimatorFactory.animateInTopView(this.mStatusBar));
        this.mAnimators.add(AnimatorFactory.animateInRightView(this.mMenu));
        if (!this.mIsVideoLoading) {
            this.mAnimators.add(AnimatorFactory.animateInBottomView(this.mMediaController));
        }
    }

    @Override
    public void onError(GeekleiVideoView iVideoView, int what, int extras, ErrorEvent errDesc) {

    }

    public boolean IsScreenLocked() {
        return mIsScreenLocked;
    }

    public void start() {
        if (!mPlayer.isPlaying()) {
            mMediaController.togglePause();
        }
    }

    public void pause() {
        if (mPlayer.isPlaying()) {
            mMediaController.togglePause();
        }
    }
}
